package com.neouton.crm.payRecords.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalLogVO;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.NoticVo;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.payRecords.entity.PaymentRecords;

import com.neouton.crm.payRecords.entity.PaymentRequest;
import com.neouton.crm.payRecords.entity.PaymentTable;
import com.neouton.crm.payRecords.mapper.PaymentRecordsMapper;
import com.neouton.crm.payRecords.mapper.PaymentRequestMapper;
import com.neouton.crm.payRecords.service.PaymentRecordsService;
import com.neouton.crm.paymentPlan.entity.PaymentPlan;
import com.neouton.crm.paymentPlan.mapper.PaymentPlanMapper;
import com.neouton.crm.paymentPlan.service.PaymentPlanService;
import com.neouton.crm.pm.entity.ContractInfoVO;
import com.neouton.crm.pm.entity.PurchaseOrderVO;
import com.neouton.crm.pm.entity.SalesProjectManageVO;
import com.neouton.crm.pm.service.IPurchaseOrdeService;
import com.neouton.crm.pm.service.SalesProjectManageService;
import com.neouton.crm.product.mapper.ProductInfoMapper;
import com.neouton.crm.receiptRecords.entity.ReceiptRecords;
import com.neouton.crm.receiptRecords.entity.ReceiptTable;
import com.neouton.crm.receiptRecords.mapper.ReceiptRecordsMapper;
import com.neouton.crm.receiptRecords.service.ReceiptRecordsService;
import com.neouton.crm.sales.entity.SalesFileRelationVO;
import com.neouton.crm.sales.mapper.SalesFileRelationMapper;
import com.neouton.crm.sales.service.SalesFileRelationService;
import com.neouton.crm.supplier.entity.SupplierVO;
import com.neouton.crm.transpondEmail.entity.TranspondEmailVO;
import com.neouton.crm.transpondEmail.mapper.TranspondEmailMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginMessageService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author Mose
* @description 针对表【payment_records(付款记录)】的数据库操作Service实现
* @createDate 2023-02-03 15:33:29
*/
@Service
public class PaymentRecordsServiceImpl implements PaymentRecordsService {

    @Resource
    private PaymentRecordsMapper paymentRecordsMapper;

    @Resource
    private IPurchaseOrdeService purchaseOrdeService;

    @Resource
    private PaymentRequestMapper paymentRequestMapper;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private PaymentPlanService paymentPlanService;

    @Resource
    private SalesFileRelationService salesFileRelationService;
    @Resource
    FeginService feginService;


    @Resource
    private ReceiptRecordsService receiptRecordsService;

    @Resource
    private PaymentPlanMapper paymentPlanMapper;

    @Resource
    private TranspondEmailMapper transpondEmailMapper;
    @Resource
    private ReceiptRecordsMapper receiptRecordsMapper;

    @Resource
    private TranspondEmailService transpondEmailService;


    @Value("${webSit.web}")
    private String webSitUrl;
    /**
     * 分页查询
     *
     *
     * @param entity
     * @return
     */
    @Override
    public List<PaymentRecords> queryPage(PaymentRecords entity) {
        List<PaymentRecords> list = paymentRecordsMapper.queryPaymentRecordsPage(entity);
        return list;
    }
    /**
     * 保存或修改付款记录
     * @param entity
     * @param token
     * @return
     */
    @Override
    public PaymentRecords savePaymentRecords(PaymentRecords entity,String token) {
        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
        //获取人员信息
        Integer businessId = this.startPayRequestApproval(token, user,"payRecords");
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 27, entity.getAskReason(), "",
                user.getUserId(),"");
        //之后更新/保存
        entity.setApprovalId(approval.getApprovalId());
        Integer purchaseOrdeId=  entity.getPurchaseOrderId();
        PurchaseOrderVO purchaseOrderVO = purchaseOrdeService.getPurchaseOrdeInfoById(purchaseOrdeId);
        entity.setPurchaseNo(purchaseOrderVO.getPurchaseNo());
        entity.setPurchaseTopic(purchaseOrderVO.getPurchaseTopic());
        paymentRequestMapper.updatePrIsNotById(entity.getPayRequestId(),"1");
        if(entity.getPayRecordsId() != null){
            PaymentRecords paymentRecord = paymentRecordsMapper.queryPayRecordInfoById(entity.getPayRecordsId());
            paymentRecordsMapper.backUpPaymentRecord(paymentRecord.getPayRecordsId(), AuthUtils.getUserId());
            paymentRecordsMapper.updatePaymentRecordsById(entity);
        }else{
            if(entity.getPaymentMoney() == null || ("").equals(entity.getPaymentMoney())){
                entity.setPaymentMoney("0.00");
            }
            if(entity.getEliminationMoney() == null|| ("").equals(entity.getEliminationMoney())) {
                entity.setEliminationMoney("0.00");
            }
             paymentRecordsMapper.savePaymentRecords(entity);

        }
        List<PaymentPlan> paymentPlans = new ArrayList<>();
        for (PaymentTable paymentTable : entity.getPaymentTable()){
            PaymentPlan paymentPlan = new PaymentPlan();
            paymentPlan.setPlanPeriod(paymentTable.getPlanPeriod());
            paymentPlan.setPurchaseOrderId(entity.getPurchaseOrderId());
            if(paymentTable.getPayedMoney() != null) {
                if (new BigDecimal(paymentTable.getPayedMoney()).compareTo(BigDecimal.ZERO) == 1) {
                    paymentPlan.setPayIsNot(2);
                } else if (new BigDecimal(paymentTable.getPayedMoney()).compareTo(BigDecimal.ZERO) == 0) {
                    paymentPlan.setPayIsNot(0);
                }
                paymentPlan.setPurchaseId(entity.getPurchaseOrderId());
            }
            paymentPlans.add(paymentPlan);
        }
        paymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);


        //修改转发人
        if(!CollectionUtils.isEmpty(entity.getTranspondUsers())) {
            transpondEmailService.insertTranspondEmailInfoByUser(entity.getApprovalId(),entity.getTranspondUsers());
        }
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvedPayRecord(entity,token,true);
        }else {
            //发送审批邮件
            //发送邮件
            String title = "【系统通知】付款记录- 流程单审批通知";
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String today = simpleDateFormat.format(date);
            String msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的付款记录审批需要处理：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(entity.getAskReason()) ? "" : entity.getAskReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>申请时间："+today+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：第"+entity.getPlanPeriod()+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";


//                    initPayRequestEmailContent(user.getLoginName(),"您有一张新的付款记录审批需要处理",approval.getApprovalCode(),
//                    AuthUtils.getUserName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());
           // CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,title,msg,token));
            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId,0,27,user.getUserId(),token));
        }

        return entity;
    }


    /**
     * 根据主键id更新
     *
     * @param entity
     */
    @Override
    public void updatePaymentRecordsById(PaymentRecords entity) {
        paymentRecordsMapper.updatePaymentRecordsById(entity);
    }
    /**
     * 查询付款记录
     * @param entity
     * @return
     */
    @Override
    public List<PaymentRecords> queryPayRecordedMoney(PaymentRecords entity) {
        List<PaymentRecords> list = paymentRecordsMapper.queryPayRecordedMoney(entity);
        if(list.size()>0){
            if(list.get(0).getPaymentTable().size() == 0) {
                list = paymentRecordsMapper.queryHistoryPayRecordedMoney(entity);
            }
            list.get(0).setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(entity.getApprovalId()));
        }
        return list;
    }
    @Override
    public PaymentRequest savePaymentRequest(PaymentRequest entity,String token) {
        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
        //获取人员信息
        Integer businessId = this.startPayRequestApproval(token, user,"payRequest");
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 25, entity.getAskReason(), "",
                user.getUserId(),"");
        //之后更新/保存
        entity.setApprovalId(approval.getApprovalId());
        Integer purchaseOrdeId=  entity.getPurchaseOrderId();
        PurchaseOrderVO purchaseOrderVO = purchaseOrdeService.getPurchaseOrdeInfoById(purchaseOrdeId);
        entity.setPurchaseNo(purchaseOrderVO.getPurchaseNo());
        List<PaymentTable> list =  new ArrayList<>() ;
        if(entity.getPayRequestId() != null){
            paymentRequestMapper.backUpPaymentRequest(entity.getPayRequestId(), AuthUtils.getUserId());
            paymentRequestMapper.backUpPaymentTable(entity.getPayRequestId(), AuthUtils.getUserId());
            entity.setApprovalId(approval.getApprovalId());
            paymentRequestMapper.updatePaymentRequestById(entity);
            for (PaymentTable paymentTable: entity.getPaymentTable()) {
                paymentTable.setApprovalId(entity.getApprovalId());
                paymentTable.setPayedMoney(String.valueOf(Float.parseFloat(paymentTable.getPayedMoney()) - Float.parseFloat(paymentTable.getPayMoney())));
                PaymentPlan paymentPlan = new PaymentPlan();
                paymentPlan.setPlanPeriod(paymentTable.getPlanPeriod());
                paymentPlan.setPurchaseOrderId(entity.getPurchaseOrderId());
                if(paymentTable.getPayRequestId() == null){
                    paymentTable.setPayRequestId(entity.getPayRequestId());
                    paymentTable.setPurchaseOrderId(entity.getPurchaseOrderId());
                    paymentTable.setPayPlanId(paymentPlanService.queryPaymentPlanByPurchaseOrderID(paymentPlan).getPayPlanId());
                    paymentPlan.setApprovalId(entity.getApprovalId());
                }
                list.add(paymentTable);
            }
            paymentRequestMapper.updatePaymentTableDataById(list,entity.getPayRequestId());
        }else{
            if(entity.getPaymentMoney() == null || ("").equals(entity.getPaymentMoney())){
                entity.setPaymentMoney("0.00");
            }
            if(entity.getEliminationMoney() == null|| ("").equals(entity.getEliminationMoney())){
                entity.setEliminationMoney("0.00");
            }

            paymentRequestMapper.savePaymentRequest(entity);
            for (PaymentTable paymentTable:entity.getPaymentTable()) {
                paymentTable.setPayRequestId(entity.getPayRequestId());
                paymentTable.setPurchaseOrderId(entity.getPurchaseOrderId());
                paymentTable.setApprovalId(approval.getApprovalId());
                PaymentPlan paymentPlan = new PaymentPlan();
                paymentPlan.setPurchaseOrderId(entity.getPurchaseOrderId());
                paymentPlan.setPlanPeriod(paymentTable.getPlanPeriod());
                paymentTable.setPayPlanId(paymentPlanService.queryPaymentPlanByPurchaseOrderID(paymentPlan).getPayPlanId());
                //List<PaymentTable> list=  paymentRecordsMapper.queryPayTablesByIdAndPlanPeriod(paymentTable);
                if(paymentTable.getPayedMoney() != null){
                    paymentTable.setPayedMoney((new BigDecimal(paymentTable.getPayedMoney()).subtract(new BigDecimal(paymentTable.getPayMoney()))).toString());
                }else{
                    paymentTable.setPayedMoney((new BigDecimal(paymentTable.getPlanMoney())).subtract(new BigDecimal(paymentTable.getPayMoney())).toString());
                }
                list.add(paymentTable);
            }
            paymentRecordsMapper.savePaymentTable(list);

        }
        //修改转发人
        if(!CollectionUtils.isEmpty(entity.getTranspondUsers())) {

            transpondEmailService.insertTranspondEmailInfoByUser(entity.getApprovalId(),entity.getTranspondUsers());
        }
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvedPayRequest(entity,token,true);
        }else {
            //发送审批邮件
            //发送邮件
//            String title = "【系统通知】付款申请 - 流程单审批通知";
////            String msg = initPayRequestEmailContent(user.getLoginName(), "您有一张新的付款申请审批需要处理", approval.getApprovalCode(),
////                    AuthUtils.getUserName(), entity.getPurchaseTopic(), entity.getPurchaseNo(), entity.getPaymentMoney(),
////                    entity.getPlanPeriod());
//            Date date = new Date();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String today = simpleDateFormat.format(date);
//            String msg ="<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                    "<div><p style='text-indent: 2em'>您好，您有一张新的付款申请审批需要处理：</p></div>"+
//                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(entity.getAskReason()) ? "" : entity.getAskReason())+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请时间："+today+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
//                    "<div><p style='text-indent: 2em'>付款期次：第"+entity.getPlanPeriod()+"期</p></div>"+
//                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
          //  CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(), null, title, msg, token));
            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId, 0, 25, user.getUserId(), token));
        }
        return entity;
    }

    @Override
    public void updatePaymentRequestById(PaymentRequest entity) {
        paymentRequestMapper.updatePaymentRequestById(entity);
    }
    /**
     * 查询付款申请
     * @param entity
     * @return
     */
    @Override
    public List<PaymentRequest> queryPayRequestMoney(PaymentRequest entity) {
        List<PaymentRequest> list = paymentRequestMapper.queryPayRequestMoney(entity);
        List<PaymentRequest> prlist = new ArrayList<>();
        if(list.size()>0 && list.size() ==1){
            if(list.get(0).getPaymentTable().size() == 0) {
                prlist.add(paymentRequestMapper.queryPayRequestHistory(entity.getApprovalId()));
                list= prlist;
            }
           list.get(0).setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(entity.getApprovalId()));
        }
        return list;
    }
    /**
     * 付款申请审批通过
     * @param entity
     * @param token
     * @return
     */
    @Override
    public Boolean approvedPayRequest(PaymentRequest entity,String token,Boolean auto) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();//最终审批人
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        String ccUser = null;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",entity.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",entity.getAppReason());
        }
        if( "出纳审批".equals(processNodeNameAndCode.getResult().getName()) ){
            user=askUser;
            workState = 1;
            todoUser = 0;
            ccUser = queryPaymentAskCC();
            String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            titel = "【系统通知】付款申请 - 流程单审批通过通知";
            msg =   "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您付款申请审批已通过：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：第"+ planPeriod+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                    initPayRequestEmailContent(user.getLoginName(),"您付款申请信息审批已通过"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());

            approvalService.approved(null,entity.getApprovalId());
//            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
//                    "",entity.getAppReason());
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            //转发人
            String bccEmail = transpondEmailService.selectTranspondEmailStr(entity.getApprovalId());
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail() , finalCcUser +","+bccEmail, titel, msg, token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    approval.getCreator(), workState, 25, todoUser, token));
        } else {
            if("商务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
                activitiVO.getCustomParams().put("finance",user.getAccount());
            }else if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
                activitiVO.getCustomParams().put("afterSales",user.getAccount());
            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("chairman").get(0);
                activitiVO.getCustomParams().put("chairman",user.getAccount());
            }else if("董事长审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("cashier").get(0);
                activitiVO.getCustomParams().put("cashier",user.getAccount());
            }
            //交由下一审批人处理
//            Map<String, Object> map = new HashMap<>();
//            map.put("user",user.getAccount());
//            activitiVO.setCustomParams(map);
            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvedPayRequest(entity,token,true);
            }else {
                workState = 0;
                todoUser = user.getUserId();
//                titel = "【系统通知】付款申请 - 流程单审批通知";
//                msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                        "<div><p style='text-indent: 2em'>您好，您有一张新的付款申请审批需要处理：</p></div>"+
//                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(entity.getAskReason()) ? "" : entity.getAskReason())+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请时间："+simpleDateFormat.format(new Date())+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
//                        "<div><p style='text-indent: 2em'>付款期次：第"+ entity.getPlanPeriod()+"期</p></div>"+
//                        "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                        initPayRequestEmailContent(user.getLoginName(), "您有一张新的付款申请信息审批需要处理"
//                        , approval.getApprovalCode(), askUser.getLoginName(), entity.getPurchaseTopic(), entity.getPurchaseNo(), entity.getPaymentMoney(),
//                        entity.getPlanPeriod());

                approvalService.updateNextApproverByApprovalId(user.getUserId(), entity.getApprovalId());
//                approvalService.insertApprovalLog(approval.getApprovalId(), "通过",
//                        "", entity.getAppReason());
//                String finalCcUser = ccUser;
//                SysUserEntity finalUser = user;
//                CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser, titel, msg, token));
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                        approval.getCreator(), workState, 25, todoUser, token));
            }

        }
        //记录日志


        return true;
    }
    /**
     * 付款申请审批驳回
     * @param entity
     * @param token
     * @return
     */
    @Override
    public Boolean rejectionPayRequest(PaymentRequest entity, String token) {
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        //ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        //驳回
        workFlowFeginService.deleteInstance(activitiVO);
        this.updatePayedRecordTableData(approval.getApprovalId());
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if("商务审批".equals(processNodeNameAndCode.getResult().getName())){
            user = askUser;
            workFlowFeginService.deleteInstance(activitiVO);
            String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
            //驳回至起点
            workState = 1;
            titel= "【系统通知】付款申请 - 流程单审批驳回通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的付款申请审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+ (StringUtils.isEmpty(entity.getAppReason()) ? "" : entity.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+simpleDateFormat.format(new Date())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：第"+ planPeriod+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";


//                    initPayRequestEmailContent(askUser.getLoginName(),"您有一张新的付款申请审批已被驳回，请修改后重新提交审批"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());
            approvalService.approvalRejection(null,entity.getApprovalId());
            todoUser = 0;
//        }else {
//            //驳回至上一节点
//            if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
//            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            }else if("董事长审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            }
//
//            workState = 0;
//            titel = "【系统通知】付款申请审批待处理通知";
//            msg =  initPayRequestEmailContent(user.getLoginName(),"您有一张新的付款申请审批已被上级驳回，需要处理"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());
//            todoUser = user.getUserId();
//            approvalService.updateNextApproverByApprovalId(user.getUserId(),entity.getApprovalId());
//        }
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",entity.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId  = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,25,todoUser,token));
        return true;
    }
    /**
     * 付款记录审批通过
     * @param entity
     * @param token
     * @return
     */
    @Override
    public Boolean approvedPayRecord(PaymentRecords entity, String token,Boolean auto) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();//最终审批人
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        SysUserEntity user =null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        String ccUser = null;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",entity.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",entity.getAppReason());
        }
        if( "出纳审批".equals(processNodeNameAndCode.getResult().getName()) ){
            user=askUser;
            workState = 1;
            todoUser = 0;
            ccUser = queryPayRecordCC();
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            paymentRequestMapper.updatePrIsNotById(entity.getPayRequestId(),"4");
            String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
            titel = "【系统通知】付款记录 - 流程单审批通过通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您付款记录审批已通过：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：第"+ planPeriod+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                    initPayRequestEmailContent(user.getLoginName(),"您付款记录信息审批已通过"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());
            approvalService.approved(null,entity.getApprovalId());
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            //转发人
            String bccEmail = transpondEmailService.selectTranspondEmailStr(entity.getApprovalId());
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser +","+bccEmail, titel, msg, token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    approval.getCreator(), workState, 27, todoUser, token));
        } else {
            if("商务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
                activitiVO.getCustomParams().put("finance",user.getAccount());
            }else if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
                activitiVO.getCustomParams().put("afterSales",user.getAccount());
            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("cashier").get(0);
                activitiVO.getCustomParams().put("cashier",user.getAccount());
            }
            paymentRequestMapper.updatePrIsNotById(entity.getPayRequestId(),"1");
            //交由下一审批人处理
//            Map<String, Object> map = new HashMap<>();
//            map.put("user",user.getAccount());
//            activitiVO.setCustomParams(map);

            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvedPayRecord(entity,token,true);
            }else {
                todoUser = user.getUserId();
                workState = 0;
//                titel = "【系统通知】付款记录 - 流程单审批通知";
//                msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                                "<div><p style='text-indent: 2em'>您好，您有一张新的付款记录审批需要处理：</p></div>"+
//                                "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName()+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(entity.getAskReason()) ? "" : entity.getAskReason())+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>申请时间："+simpleDateFormat.format(new Date())+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
//                                "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
//                                "<div><p style='text-indent: 2em'>付款期次：第"+ entity.getPlanPeriod()+"期</p></div>"+
//                                "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                                "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                                "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                                "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                        initPayRequestEmailContent(user.getLoginName(),"您有一张新的付款记录审批需要处理"
//                        ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                        entity.getPlanPeriod());
                approvalService.updateNextApproverByApprovalId(user.getUserId(),entity.getApprovalId());
                //记录日志
//                approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
//                        "",entity.getAppReason());
//                String finalCcUser = ccUser;
//                SysUserEntity finalUser = user;
//                CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                        approval.getCreator(),workState,27,todoUser,token));
            }
        }


        return true;
    }
    /**
     * 付款记录审批驳回
     * @param entity
     * @param token
     * @return
     */
    @Override
    public Boolean rejectionPayRecord(PaymentRecords entity, String token) {
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        //ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        workFlowFeginService.deleteInstance(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if("商务审批".equals(processNodeNameAndCode.getResult().getName())){
            user = askUser;
            workFlowFeginService.deleteInstance(activitiVO);
            //驳回至起点
            String planPeriod = NumberToCnUtil.strToChineseLower(entity.getPlanPeriod());
            workState = 1;
            titel= "【系统通知】付款记录 - 流程单审批驳回通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的付款记录审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+ (StringUtils.isEmpty(entity.getAppReason()) ? "" : entity.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+simpleDateFormat.format(new Date())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+entity.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单编号："+entity.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：第"+ planPeriod+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                    initPayRequestEmailContent(askUser.getLoginName(),"您有一张新的付款记录信息审批已被驳回，请修改后重新提交审批"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());

            approvalService.approvalRejection(null,entity.getApprovalId());
            paymentRequestMapper.updatePrIsNotById(entity.getPayRequestId(),"3");
            todoUser = 0;
//        }else {
//            //驳回至上一节点
//            if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
//            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())) {
//                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            }
//            workState = 0;
//            titel = "【系统通知】付款记录信息审批待处理通知";
//            msg =  initPayRequestEmailContent(user.getLoginName(),"您有一张新的付款记录信息审批已被上级驳回，需要处理"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),entity.getPurchaseTopic(),entity.getPurchaseNo(),entity.getPaymentMoney(),
//                    entity.getPlanPeriod());
//            todoUser = user.getUserId();
//            approvalService.updateNextApproverByApprovalId(user.getUserId(),entity.getApprovalId());
//        }
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",entity.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId  = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,27,todoUser,token));
        return true;
    }


    @Override
    public void updatePayedRecordTableData(Integer approvalId) {
        List<PaymentTable> paymentTables = paymentRequestMapper.queryPaymentTablesByApprovalId(approvalId);
        List<PaymentPlan> paymentPlans = new ArrayList<>();
        List<PaymentTable> list = new ArrayList<>();
        for (PaymentTable paymentTable: paymentTables) {
            paymentTable.setPayedMoney(((new BigDecimal(paymentTable.getPayedMoney()))
                    .add(new BigDecimal(paymentTable.getPayMoney()))).toString());
            PaymentPlan paymentPlan = new PaymentPlan();
            if((new BigDecimal(paymentTable.getPayedMoney())).compareTo(new BigDecimal(paymentTable.getPlanMoney()))==0 ){
                paymentPlan.setPayIsNot(1);
            }else if((new BigDecimal(paymentTable.getPayedMoney())).compareTo(new BigDecimal(paymentTable.getPlanMoney()))== -1 ){
                paymentPlan.setPayIsNot(2);
            }else{
                paymentPlan.setPayIsNot(0);
            }
            paymentPlan.setPlanPeriod(paymentTable.getPlanPeriod());
            paymentPlan.setPurchaseId(paymentTable.getPurchaseOrderId());
            paymentPlans.add(paymentPlan);
            list.add(paymentTable);
        }
        paymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);
        paymentRequestMapper.updateRequestTableData(list, approvalId);
    }

    @Override
    public PageUtil<PaymentRecords> queryToDoPaymentRecordsListInfo(IPage<PaymentRecords> page, PaymentRecords paymentRecords,  String token) {
        if (paymentRecords.getOrderByProp() != null) {
            paymentRecords.setOrderByProp(StringUtils.camelToUnderline(paymentRecords.getOrderByProp()));
        }
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(27);
        List<ApprovalVO> appList = new ArrayList<>();
        if ("todo".equals(paymentRecords.getParamType())) {
            appList = approvalService.queryApprovalByPage(approvalVO);
        } else if ("done".equals(paymentRecords.getParamType())) {
            appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        } else {
            appList = approvalService.queryApprovalRecordByType(approvalVO, token);
        }
        if (appList == null || appList.isEmpty()) {
            return new PageUtil(new PageDTO());
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            if (arrayList.size() > 0) {
                paymentRecords.setApprovalIds(arrayList);
            } else {
                arrayList.add(0);
                paymentRecords.setApprovalIds(arrayList);
            }
            IPage<PaymentRecords> iPage = paymentRecordsMapper.queryPaymentRecordsListInfo(page, paymentRecords, null);
            List<PaymentRecords> list = iPage.getRecords();
            if (!list.isEmpty()) {
                BigDecimal paymentMoneyPage = new BigDecimal(0);
                BigDecimal eliminationMoneyPage = new BigDecimal(0);
                for (PaymentRecords prvo : list) {
                    prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByPayRequestId(prvo.getPayRequestId()));
                    if (StringUtils.isNotEmpty(prvo.getPaymentMoney())) {
                        paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                    }
                    if (StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                        eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                    }
                }
                list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
                list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
                iPage.setRecords(list);
            }

            return new PageUtil<>(iPage);
        }
    }

    @Override
    public PageUtil<PaymentRequest> queryToDoPaymentRequestListInfo(IPage<PaymentRequest> page, PaymentRequest paymentRequest, String token) {
        if (paymentRequest.getOrderByProp() != null) {
            paymentRequest.setOrderByProp(StringUtils.camelToUnderline(paymentRequest.getOrderByProp()));
        }
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(25);
        List<ApprovalVO> appList = new ArrayList<>();
        if ("todo".equals(paymentRequest.getParamType())) {
            appList = approvalService.queryApprovalByPage(approvalVO);
        } else if ("done".equals(paymentRequest.getParamType())) {
            appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        } else {
            appList = approvalService.queryApprovalRecordByType(approvalVO, token);
        }
        if (appList == null || appList.isEmpty()) {
            return new PageUtil(new PageDTO());
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            if (arrayList.size() > 0) {
                paymentRequest.setApprovalIds(arrayList);
            } else {
                arrayList.add(0);
                paymentRequest.setApprovalIds(arrayList);
            }
            IPage<PaymentRequest> iPage = paymentRequestMapper.queryPaymentRequestListInfo(page, paymentRequest, null);
            List<PaymentRequest> list = iPage.getRecords();
            if (!list.isEmpty()) {
                BigDecimal paymentMoneyPage = new BigDecimal(0);
                BigDecimal eliminationMoneyPage = new BigDecimal(0);
                for (PaymentRequest prvo : list) {
                    prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByApprovalId(prvo.getApprovalId()));
                    if (StringUtils.isNotEmpty(prvo.getPaymentMoney())) {
                        paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                    }
                    if (StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                        eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                    }
                }
                list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
                list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
                iPage.setRecords(list);

            }
            return new PageUtil<>(iPage);
        }
    }

    @Override
    public Boolean deletePayedRequestById(Integer payRequestId) {
        return paymentRequestMapper.deletePayedRequestById(payRequestId);
    }

    @Override
    public Boolean deletePayRecordsById(Integer payRecordsId) {
        PaymentRecords paymentRecords =paymentRecordsMapper.queryPayRecordInfoById(payRecordsId);
        paymentRequestMapper.updatePrIsNotById(paymentRecords.getPayRequestId(),"0");
        return  paymentRecordsMapper.deletePayRecordsById(payRecordsId);
    }

    @Override
    public void updatePayRequestAfterPass(PaymentRequest paymentRequest, String token) {
        // 将修改后的数据放入redis缓存
        Map<String,Object> projectInfoMap = new HashMap<>();
        projectInfoMap.put(paymentRequest.getPayRequestId().toString(),paymentRequest);
        feginService.setCacheInfo(Constants.CACHE_PAYREQUEST + paymentRequest.getPayRequestId(),projectInfoMap,token);
    }

    @Override
    public PaymentRequest queryReceiptRecordFromCache(int payRequestId, String token) {
        String managerCacheKey = Constants.CACHE_PAYREQUEST+payRequestId;
        ResponseAPI cacheInfo = feginService.getCacheInfo(managerCacheKey,String.valueOf(payRequestId), token);
        String jsonObject= JSON.toJSONString(cacheInfo.getResult());
        //将json转成需要的对象
        PaymentRequest paymentRequest = JSONObject.parseObject(jsonObject,PaymentRequest.class);
        return paymentRequest;
    }

    @Override
    public void updatePrIsNotById(Integer payRequestId) {
         paymentRequestMapper.updatePrIsNotById(payRequestId,"2");
    }

    /**
     * 通过付款申请表主键查询历史
     * @param approvalId
     * @return
     */
    public PaymentRequest queryPayRequestHistory(Integer approvalId){
        PaymentRequest paymentRequest = paymentRequestMapper.queryPayRequestHistory(approvalId);
        if(paymentRequest == null || paymentRequest.getPaymentTable().size() == 0){
            PaymentRequest payReq = new PaymentRequest();
            payReq.setApprovalId(approvalId);
            paymentRequest = this.queryPayRequestMoney(payReq).get(0);
        }
        paymentRequest.setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return  paymentRequest;
    }
    /**
     * 通过付款记录表主键查询历史
     * @param approvalId
     * @return
     */
    public PaymentRecords queryPayRecordHistory(Integer approvalId){
        PaymentRecords paymentRecords = paymentRecordsMapper.queryPayRecordHistory(approvalId);
        if(paymentRecords == null){
            PaymentRecords payReq = new PaymentRecords();
            payReq.setApprovalId(approvalId);
            paymentRecords = this.queryPayRecordedMoney(payReq).get(0);
        }
        paymentRecords.setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return paymentRecords;
    }

    @Override
    public PageUtil<PaymentRequest> queryPaymentRequestListInfo(IPage<PaymentRequest> page, PaymentRequest paymentRequest, List<SysUserEntity> userList, String token) {
        if (paymentRequest.getOrderByProp() != null) {
            paymentRequest.setOrderByProp(StringUtils.camelToUnderline(paymentRequest.getOrderByProp()));
        }
        IPage<PaymentRequest> iPage = paymentRequestMapper.queryPaymentRequestListInfo(page, paymentRequest, userList);
        List<PaymentRequest> list  =  iPage.getRecords();
        if(!list.isEmpty()){
            BigDecimal paymentMoneyPage = new BigDecimal(0);
            BigDecimal eliminationMoneyPage = new BigDecimal(0);
            for (PaymentRequest  prvo: list) {
                prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByApprovalId(prvo.getApprovalId()));
                if(StringUtils.isNotEmpty(prvo.getPaymentMoney())){
                    paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                }
                if(StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                    eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                }
            }
            list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
            list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
            iPage.setRecords(list);

        }
        return new PageUtil<>(iPage);
    }

    @Override
    public List<PaymentRequest> queryPaymentRequestListInfo(PaymentRequest paymentRequest, List<SysUserEntity> userList, String token) {
        if (paymentRequest.getOrderByProp() != null) {
            paymentRequest.setOrderByProp(StringUtils.camelToUnderline(paymentRequest.getOrderByProp()));
        }
        List<PaymentRequest> list = paymentRequestMapper.queryPaymentRequestListInfo(paymentRequest, userList);

        return list;
    }

    @Override
    public PageUtil<PaymentRecords> queryPaymentRecordsListInfo(IPage<PaymentRecords> page, PaymentRecords paymentRecords, List<SysUserEntity> userList, String token) {
        if (paymentRecords.getOrderByProp() != null) {
            paymentRecords.setOrderByProp(StringUtils.camelToUnderline(paymentRecords.getOrderByProp()));
        }
        IPage<PaymentRecords> iPage = paymentRecordsMapper.queryPaymentRecordsListInfo(page, paymentRecords, userList);
        List<PaymentRecords> list  =  iPage.getRecords();
        if(!list.isEmpty()){
            BigDecimal paymentMoneyPage = new BigDecimal(0);
            BigDecimal eliminationMoneyPage = new BigDecimal(0);
            for (PaymentRecords  prvo: list) {
                prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByPayRequestId(prvo.getPayRequestId()));
                if(StringUtils.isNotEmpty(prvo.getPaymentMoney())){
                    paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                }
                if(StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                    eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                }
            }
            list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
            list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
            iPage.setRecords(list);
        }

        return new PageUtil<>(iPage);
    }

    @Override
    public List<PaymentRecords> queryPaymentRecordsListInfo(PaymentRecords paymentRecords, List<SysUserEntity> userList, String token) {
        if (paymentRecords.getOrderByProp() != null) {
            paymentRecords.setOrderByProp(StringUtils.camelToUnderline(paymentRecords.getOrderByProp()));
        }
        List<PaymentRecords> list = paymentRecordsMapper.queryPaymentRecordsListInfo(paymentRecords, userList);
        return list;
    }

    @Override
    public void exportPaymentRequestInfo(HttpServletResponse response, List<PaymentRequest> list, String token) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> statesList = new ArrayList<>();
        statesList.add("approvalStatus");
        JSONObject userObject = feginService.getUserInfo(token);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", statesList);
        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("payMethod");
        classfiedCode.add("receiveInvoice");
        classfiedCode.add("payIsNot");
        classfiedCode.add("payPlanPeriodNum");
        Map<String, List<DictionaryLookupItemVO>> listMap = dictionaryService.queryDictionaryLookupInfo(1, classfiedCode);
        for (int i = 0; i < list.size(); i++) {
            PaymentRequest prVO = list.get(i);
            prVO.setPayRequestId(i+1);
            prVO.setSupplierName(selSupplierName(prVO.getSupplier().getSupplierId()));
            String str = "";
            String [] planPeriods;
            if(prVO.getPlanPeriod().indexOf(",")>0){
                planPeriods = prVO.getPlanPeriod().split(",");
                for ( int j =0 ;j<planPeriods.length ;j ++) {
                    if(j==planPeriods.length -1){
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+"";
                    }else{
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+",";
                    }

                }
                prVO.setPlanPeriodName(str);
            }else{
                prVO.setPlanPeriodName((String)getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(prVO.getPlanPeriod() + ""));
            }
            prVO.setHeadName((String)getUserNameById(userObject).get(prVO.getHead().getUserId()));
            prVO.setOwnerName((String)getUserNameById(userObject).get(prVO.getOwner().getUserId()));
            prVO.setPayMethodName((String) getCRMDictionaryNameByCode("payMethod", listMap).get(prVO.getPayMethod() + ""));
            prVO.setReceiveInvoiceName((String) getCRMDictionaryNameByCode("receiveInvoice", listMap).get(prVO.getReceiveInvoice() + ""));
            prVO.setApprovalStatusName((String)getDictionaryNameByCode("approvalStatus",jsonObject).get(prVO.getApproval().getApprovalStatus() + ""));
            prVO.setPayIsNotName((String) getCRMDictionaryNameByCode("payIsNot", listMap).get(prVO.getPayIsNot() + ""));
            if(prVO.getPurchaseCategories() != null  && prVO.getPurchaseOrder() != null){
                if(prVO.getPurchaseCategories() == 0){
                    prVO.setPurchaseCategoriesStr("机会采购");
                    prVO.setProjectManageTheme(prVO.getPurchaseOrder().getOpportunityTheme());
                }else{
                    prVO.setPurchaseCategoriesStr("项目采购");
                    prVO.setProjectManageTheme(prVO.getPurchaseOrder().getProjectManageTheme());
                }
            }
            prVO.setMoneyDateTime(dateFormat.format(prVO.getMoneyDate()));
        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String templatePath = String.valueOf(properties.get("report.paymentRequestTemplate"));
        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("paymentRequestInfo",list);
        ReportUtils.exportExcel(params,map,"付款申请信息",response);
    }


    public List<PaymentTable> queryPayTablesByIdAndPlanPeriod(PaymentTable entity) {
        return paymentRecordsMapper.queryPayTablesByIdAndPlanPeriod(entity);
    }

    @Override
    public void exportPaymentRecordsInfo(HttpServletResponse response, List<PaymentRecords> list, String token) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> statesList = new ArrayList<>();

        statesList.add("receiveInvoice");
        statesList.add("approvalStatus");
        JSONObject userObject = feginService.getUserInfo(token);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", statesList);
        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("payPlanPeriodNum");
        classfiedCode.add("payMethod");
        Map<String, List<DictionaryLookupItemVO>> listMap = dictionaryService.queryDictionaryLookupInfo(1, classfiedCode);
        for (int i = 0; i < list.size(); i++) {
            PaymentRecords prVO = list.get(i);
            prVO.setPayRecordsId(i+1);
            if(prVO.getSupplier() !=null){
                prVO.setSupplierName(selSupplierName(prVO.getSupplier().getSupplierId()));
            }
            String str = "";
            String [] planPeriods;
            if(prVO.getPlanPeriod() != null){


                if(prVO.getPlanPeriod().indexOf(",")>0){
                    planPeriods = prVO.getPlanPeriod().split(",");
                    for ( int j =0 ;j<planPeriods.length ;j ++) {
                        if(j==planPeriods.length -1){
                            str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+"";
                        }else{
                            str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+",";
                        }

                    }
                    prVO.setPlanPeriodName(str);
                }else{
                    prVO.setPlanPeriodName((String)getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(prVO.getPlanPeriod() + ""));
                }
            }
            prVO.setHeadName((String)getUserNameById(userObject).get(prVO.getHead().getUserId()));
            prVO.setOwnerName((String)getUserNameById(userObject).get(prVO.getOwner().getUserId()));
            prVO.setPayMethodName((String) getCRMDictionaryNameByCode("payMethod", listMap).get(prVO.getPayMethod() + ""));
//            prVO.setReceiveInvoiceName((String) getDictionaryNameByCode("receiveInvoice", jsonObject).get(prVO.getReceiveInvoice() + ""));
            if(prVO.getPurchaseCategories() != null  && prVO.getPurchaseOrder() != null){
                if(prVO.getPurchaseCategories() == 0){
                    prVO.setPurchaseCategoriesStr("机会采购");
                    prVO.setProjectManageTheme(prVO.getPurchaseOrder().getOpportunityTheme());
                }else{
                    prVO.setPurchaseCategoriesStr("项目采购");
                    prVO.setProjectManageTheme(prVO.getPurchaseOrder().getProjectManageTheme());
                }
            }
            prVO.setApprovalStatusName((String)getDictionaryNameByCode("approvalStatus",jsonObject).get(prVO.getApproval().getApprovalStatus() + ""));
            if(prVO.getMoneyDate() != null){
                prVO.setMoneyDateTime(dateFormat.format(prVO.getMoneyDate()));
            }

        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String templatePath = String.valueOf(properties.get("report.paymentRecordsTemplate"));
        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("paymentRecordsInfo",list);
        ReportUtils.exportExcel(params,map,"付款记录信息",response);
    }

    private String selSupplierName(Integer supplierId) {
        List<SupplierVO> list = productInfoMapper.querySuppliers();
        if (!CollectionUtils.isEmpty(list)) {
            for (SupplierVO item : list) {
                if (item.getSupplierId().equals(supplierId)) {
                    return item.getSupplierName();
                }
            }
            return null;
        }
        return null;
    }

    private Map getCRMDictionaryNameByCode(String itemCode, Map listMap) {
//        LinkedHashMap linkedHashMap = (LinkedHashMap) listMap.get("result");
        List<DictionaryLookupItemVO> dataDictionaryArray = (List) listMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (DictionaryLookupItemVO item : dataDictionaryArray) {
                map.put(item.getItemCode(), item.getItemName());
            }
            return map;
        }
        return null;
    }

    private Map getDictionaryNameByCode(String itemCode, JSONObject jsonObject) {
        LinkedHashMap linkedHashMap = (LinkedHashMap) jsonObject.get("result");
        List<Map> dataDictionaryArray = (List) linkedHashMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put(item.get("itemCode").toString(), item.get("itemName").toString());
            }
            return map;
        }
        return null;
    }

    private Map getUserNameById(JSONObject jsonObject) {
        List<Map> dataDictionaryArray = (List) jsonObject.get("result");
        Map<Integer, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put((Integer) item.get("userId"), (String) item.get("loginName"));
            }
            return map;
        }
        return null;
    }

    /**
     * 开启审批流程
     * @param token
     * @param user
     * @param name 模块名称
     * @return
     */
    private Integer startPayRequestApproval(String token,SysUserEntity user,String name){
        ActivitiVO activitiVO = new ActivitiVO();
        ResponseAPI<ActivitiVO> responseAPI;
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        if("payRequest".equals(name)){
            activitiVO.setProcessName("付款申请审批");
            activitiVO.setProcessCode("payment_request_approval");
            HashMap<String,Object> customParams = new HashMap<>();
            SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
            customParams.put("commercialSpecialist",business.getAccount());
//            SysUserEntity finance = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            customParams.put("finance",finance.getAccount());
//            SysUserEntity afterSales = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            customParams.put("afterSales",afterSales.getAccount());
//
//            SysUserEntity chairman = dictionaryService.queryMenuUserIdsByCode("chairman").get(0);
//            customParams.put("chairman",chairman.getAccount());
            activitiVO.setCustomParams(customParams);

        }else{
            activitiVO.setProcessName("付款记录审批");
            activitiVO.setProcessCode("payment_records_approval");
            HashMap<String,Object> customParams = new HashMap<>();
            SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
            customParams.put("commercialSpecialist",business.getAccount());
//            SysUserEntity finance = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            customParams.put("finance",finance.getAccount());
//            SysUserEntity afterSales = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            customParams.put("afterSales",afterSales.getAccount());
            activitiVO.setCustomParams(customParams);
        }
        responseAPI = workFlowFeginService.startProcessByDesignCodeVersionBatchCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    /**
     *  生成邮件内容
     * @param userName
     * @param msgTopic
     * @param approvalCode
     * @param askeUserName
     * @param contractTopic
     * @param contractNo
     * @param contractAmount
     * @param planPeriod
     * @return
     */
    private String initPayRequestEmailContent(String userName,String msgTopic,String approvalCode,String askeUserName,
                                              String contractTopic, String contractNo,
                                              String contractAmount,String planPeriod){
        String msg =   "<div><p >" + "尊敬的" + userName + "：</p></div>" +
                "<div><p style='text-indent: 2em'>您好，"+msgTopic +"：</p></div>"+
                "<div><p style='text-indent: 2em'>事项编号："+approvalCode+"</p></div>"+
                "<div><p style='text-indent: 2em'>申请人："+askeUserName+"</p></div>"+
                "<div><p style='text-indent: 2em'>采购名称："+contractTopic+"</p></div>"+
                "<div><p style='text-indent: 2em'>采购单编号："+contractNo+"</p></div>"+
                "<div><p style='text-indent: 2em'>付款金额："+contractAmount+"元</p></div>"+
                "<div><p style='text-indent: 2em'>付款期次：第"+planPeriod+"期</p></div>";
        if(msgTopic.contains("处理")){
            msg += "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }else {
            msg += "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }
        return msg;
    }




    /**
     * 付款记录抄送人
     * @return
     */
    private String queryPayRecordCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("payRecordCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    /**
     * 付款记录抄送人
     * @return
     */
    private String queryPaymentAskCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("paymentAskCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    /**
     * 批量新增文件记录
     * @param salesFileRelationVOS
     * @param paymentRecords
     */
    public void insertFileInfo(List<SalesFileRelationVO> salesFileRelationVOS,PaymentRecords paymentRecords) {
        List<SalesFileRelationVO> salesFileRelationVOList = new ArrayList<>();
        SalesFileRelationVO salesFileRelation = new SalesFileRelationVO();
        for (SalesFileRelationVO salesFileRelationVO: salesFileRelationVOS) {
            salesFileRelation.setSalesRelationId(paymentRecords.getPayRecordsId());
            salesFileRelation.setFileClass(5);
            salesFileRelation.setCreator(AuthUtils.getUserId());
            salesFileRelation.setCreateDataTime(new Timestamp(new Date().getTime()));
            salesFileRelation.setFileId(salesFileRelationVO.getFileId());
            salesFileRelation.setFileName(salesFileRelationVO.getFileName());
            salesFileRelation.setContentType(salesFileRelationVO.getContentType());
            salesFileRelation.setFlag(1);
            salesFileRelationVOList.add(salesFileRelation);
        }
        salesFileRelationService.saveBatch(salesFileRelationVOList);
    }

    private void updatePaymentPlanMoneyAndState(PaymentRecords paymentRecords) {
        //驳回提交
//        List<PaymentPlan> paymentPlans = new ArrayList<>();
//        PaymentPlan paymentPlan = new PaymentPlan();
//        paymentPlan.setPurchaseOrderId(paymentRecords.getPurchaseOrderId());
//        paymentPlans = paymentPlanService.queryPayPlanBackByPidAndPlanPeriod(paymentPlan);
//        if(paymentRecords.getPayRecordsId() != null){
//            PaymentPlan paymentPlan = new PaymentPlan();
//            paymentPlan.setPurchaseOrderId(paymentRecords.getPurchaseOrderId());
//            paymentPlans = paymentPlanService.queryPayPlanBackByPidAndPlanPeriod(paymentPlan);
//            paymentPlanService.updatePayPlansByIdAndPlanPeriod(paymentPlans);
//        }
        //新增
//        ReceiptRecords receiptRecords = new ReceiptRecords();
//        receiptRecords.setPurchaseOrderId(paymentRecords.getPurchaseOrderId());
//        List<ReceiptRecords> receiptRecordsList = receiptRecordsService.queryReceiptRecordedMoney(receiptRecords);
//        List<PaymentRecords> recordsList = this.queryPayRecordedMoney(paymentRecords);
//        List<String> list = new ArrayList<>();
//        List<String> recordList = new ArrayList<>();
//        //将收票记录的所有期次记录
//        for (ReceiptRecords rece: receiptRecordsList) {
//            if(rece.getPlanPeriod().indexOf(",")>0 ){
//                list.addAll(Arrays.asList(rece.getPlanPeriod().split(",")));
//            }else{
//                list.add(rece.getPlanPeriod());
//            }
//        }
//        //将付款记录的所有期次记录
//        for (PaymentRecords pRecord: recordsList) {
//            if(pRecord.getPlanPeriod().indexOf(",")>0 ){
//                recordList.addAll(Arrays.asList(pRecord.getPlanPeriod().split(",")));
//            }else{
//                recordList.add(pRecord.getPlanPeriod());
//            }
//        }
//        if(paymentRecords.getPayRecordsId() == null){
//            recordList.addAll(Arrays.asList(paymentRecords.getPlanPeriod().split(",")));
//        }
//        PaymentPlan paymentPlan = new PaymentPlan();
//        paymentPlan.setPurchaseOrderId(paymentRecords.getPurchaseOrderId());
//        //获取重复记录所对应的付款计划
//        List<PaymentPlan> paymentPlans1 =  paymentPlanService.queryPayPlanByPidAndPlanPeriod(paymentPlan);
//        List<PaymentPlan> payPlans =  new ArrayList<>();
//        for (PaymentPlan payPlan: paymentPlans1) {
//            if(payPlan.getReceiveInvoice()==0){
//                Map<String,Integer> repeatmap =  this.getRepetStrCount(list);
//                int receRecordsCount= repeatmap.get(payPlan.getPlanPeriod());
//                Map<String,Integer> repeatmap1 =  this.getRepetStrCount(recordList);
//                int payRecordsCount = 0;
//                if(repeatmap1.get(payPlan.getPlanPeriod()) != null){
//                    payRecordsCount= repeatmap1.get(payPlan.getPlanPeriod());
//
//                    if(receRecordsCount == payRecordsCount){
//                        payPlan.setPayIsNot(0);
//                    }else{
//                        payPlan.setPayIsNot(2);
//                    }
//                }
//            }else if(payPlan.getReceiveInvoice()==2){
//                payPlan.setPayIsNot(2);
//            }
//            payPlans.add(payPlan);
//        }
//        paymentPlanMapper.backUpPayPlan(paymentRecords.getPurchaseOrderId(),AuthUtils.getUserId());
//        paymentPlanService.updatePayPlansByIdAndPlanPeriod(payPlans);
    }

    //获取字符串在字符串集合中出现的次数
    private Map<String,Integer> getRepetStrCount(List<String> list) {
        Map<String,Integer> repeatmap = new HashMap<>();
        if(list.size()>0){
            for (String str : list) {
                int count = 1;
                if (repeatmap.get(str)!=null) {
                    count = repeatmap.get(str) + 1;
                }
                repeatmap.put(str,count);
            }
        }
        return repeatmap;
    }
}
